package com.ebuy.dao;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import com.ebuy.factory.DBConnectionFactory;
import com.ebuy.model.Product;
import com.mysql.jdbc.PreparedStatement;

public class ProductDAO {

	private static final String CREATE_PRODUCT = "INSERT INTO product (type, name, description, price, stocks) VALUES (?,?,?,?,?)";
	private static final String GET_ALL_PRODUCT = "SELECT * FROM product;";

	public Product createProduct(Product product) {
		Connection conn = DBConnectionFactory.getInstance().getConnection();

		try {
			PreparedStatement st = (PreparedStatement) conn.prepareStatement(
					CREATE_PRODUCT, PreparedStatement.RETURN_GENERATED_KEYS);

			st.setInt(1, product.getType().getId());
			st.setString(2, product.getName());
			st.setString(3, product.getDescription());
			st.setString(4, "" + product.getPrice());
			st.setInt(5, product.getStocks());

			int affectedRows = st.executeUpdate();

			if (affectedRows > 0) {
				ResultSet keys = st.getGeneratedKeys();
				if (keys.next()) {
					product.setId(keys.getInt(1));
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (conn != null) {
				try {
					conn.close();
				} catch (SQLException e) {
				}
			}
		}

		return product;
	}

	public ArrayList<Product> getAllProduct() {
		ArrayList<Product> arr = new ArrayList<Product>();
		Connection conn = DBConnectionFactory.getInstance().getConnection();

		try {
			PreparedStatement st = (PreparedStatement) conn
					.prepareStatement(GET_ALL_PRODUCT);

			ResultSet rs = st.executeQuery();

			ProductTypeDAO dao = new ProductTypeDAO();
			while (rs.next()) {
				Product p = new Product();

				p.setId(rs.getInt("id"));
				p.setType(dao.getSingleProductType(rs.getInt("type")));
				p.setName(rs.getString("name"));
				p.setDescription(rs.getString("description"));
				p.setPrice(Float.parseFloat("" + rs.getString("price")));
				p.setStocks(rs.getInt("stocks"));

				arr.add(p);
			}

			if (st != null) {
				st.close();
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (conn != null) {
				try {
					conn.close();
				} catch (SQLException e) {
				}
			}
		}

		if (arr.size() > 0) {
			return arr;
		} else {
			return null;
		}
	}

}
